<template>
  <el-dialog v-model="showModel" title="选择商品" width="1300px" @opened="handleOpen" @close="handleClose" destroy-on-close>
    <div class="goods-list">
      <div class="side left">
        <div class="title">全部商品</div>

        <search-bar>
          <template #normal>
            <el-form-item label="商品名称">
              <el-input v-model="searchFormModel.name" clearable placeholder="请输入商品名称"></el-input>
            </el-form-item>

            <el-form-item label="商品分类" prop="categoryId">
              <el-select v-model="searchFormModel.categoryId" placeholder="请选择商品分类" clearable>
                <el-option v-for="item in goodsCateList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </template>
        </search-bar>

        <div class="list" v-loading="loadingL">
          <div class="goods-item" :class="{'goods-item__selected': checkSelected(item)}" v-for="item in goodsList" @click="selectLeftGoods(item)">
            <div class="top-wrapper">
              <img class="img" :src="showItem(item, 'thumbnailUrl')" />
              <div class="name">
                {{ showItem(item, 'name') }}
              </div>
            </div>
            <div class="line">售价：{{ getPayMoney(item) }}</div>
          </div>
        </div>

        <el-pagination
            v-model:current-page="currentPageL"
            v-model:page-size="pageSizeL"
            :total="totalL"
            layout="total, prev, pager, next, jumper"
        />
      </div>

      <div class="middle operation">
        <div class="title">操作</div>
        <div class="button-list">
          <el-button type="danger" @click="clearAll">清空全部已选择</el-button>
        </div>
      </div>

      <div class="side right">
        <div class="title">已选择商品</div>
        <div class="list">
          <div class="goods-item" v-for="item in _selected" @click="selectRightGoods(item)">
            <div class="top-wrapper">
              <img class="img" :src="showItem(item, 'thumbnailUrl')" />
              <div class="name">
                {{ showItem(item, 'name') }}
              </div>
            </div>
            <div class="line">售价：{{ getPayMoney(item) }}</div>
          </div>
        </div>
<!--        <el-pagination-->
<!--            v-model:current-page="currentPageR"-->
<!--            v-model:page-size="pageSizeR"-->
<!--            :total="totalR"-->
<!--            layout="total, prev, pager, next, jumper"-->
<!--        />-->
      </div>
    </div>

    <template #footer>
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="confirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { WritableComputedRef} from "vue";
import {getPage} from "@/api/actapp";
import {useMallConfig} from "@/views/pointsMall/compositions/useMallConfig";
import {useGetGoodsCategory} from "@/views/pointsMall/compositions/useGetGoodsCategory";
import {debounce} from "@/utils";

const props = defineProps<{
  show: boolean;
  selected: {
    id: string
  }[];
  searchForm?: object,
  withProducts?: boolean
  multiSelect?: boolean
}>()

const emits = defineEmits<{
  (e: "update:show", value: boolean): void;
  (e: "confirm", value: {id: string}[]): void;
}>()

const { mallConfig } = useMallConfig();
const { goodsCateList, getGoodsCate } = useGetGoodsCategory();

const showModel:WritableComputedRef<boolean> = computed({
  get() {
    return props.show
  },
  set(newValue) {
    emits("update:show", newValue)
  }
})

// 左侧列表
const goodsList = ref(new Map());
const currentPageL = ref(1);
const pageSizeL = ref(12);
const totalL = ref(0);
const loadingL = ref(false);
const searchFormModel = reactive({
  categoryId: "",
  name: "",
  ...props?.searchForm ?? {},
})
const getGoodsList = async () => {
  loadingL.value = true
  const rs = await getPage({
    mallId: mallConfig.value.id,
    onlineStatus: 1,
    withProducts: props.withProducts,
    currentPage: currentPageL.value,
    showCount: pageSizeL.value,
    ...searchFormModel, // 其他搜索参数
  });
  goodsList.value.clear();
  (rs.payload ?? []).forEach(item => {
    goodsList.value.set(item.id, JSON.parse(JSON.stringify(item)))
  })
  loadingL.value = false;
}

const search = () => {
  currentPageL.value = 1;
  getGoodsList();
}

const debounceSearch = debounce(search, 700, false);

watch(searchFormModel, () => {
  currentPageL.value = 1;
  debounceSearch();
}, {
  deep: true
})

watch([currentPageL, pageSizeL, totalL], () => {
  getGoodsList();
})

const selectLeftGoods = (mapItem: [string, any]) => {
  const [id, item] = mapItem
  if (_selected.value.has(id)) {
    _selected.value.delete(id);
  } else {
    if (props.multiSelect) {
      _selected.value.set(id, JSON.parse(JSON.stringify(item)));
    } else {
      _selected.value.clear();
      _selected.value.set(id, JSON.parse(JSON.stringify(item)));
    }
  }
}

// 右侧列表
const currentPageR = ref(1);
const pageSizeR = ref(12);
const totalR = ref(0);
const _selected = ref(new Map());
const getSelected = () => {
  (props.selected ?? []).forEach(item => {
    _selected.value.set(item.id, JSON.parse(JSON.stringify(item)))
  })
}

const checkSelected = (mapItem: [string, any]) => {
  // console.log(mapItem)
  const [id, item] = mapItem
  // console.log("check item", id)
  return _selected.value.has(id)
}

const selectRightGoods = (mapItem: [string, any]) => {
  const [id, item] = mapItem
  _selected.value.delete(id);
}

const showItem = (item: [string, any], key: string) => {
  const [,{[key]: target}] = item
  return target
}

const getPayMoney = (mapItem: [string, any]) => {
  // console.log("paymoney", mapItem)
  const [, item] = mapItem
  if (item.showMinPrice && item.showMinCurrencyPrice) {
    return "¥" + (item.showMinPrice / 100) + "+" + item.showMinCurrencyPrice + item.showCurrencyNames
  } else if (!item.showMinPrice && item.showMinCurrencyPrice) {
    return item.showMinCurrencyPrice + item.showCurrencyNames
  } else if (item.showMinPrice && !item.showMinCurrencyPrice) {
    return "¥" + (item.showMinPrice / 100)
  } else {
    return ""
  }
}

// 中间操作按钮
const clearAll = () => {
  _selected.value.clear();
}

const cancel = () => {
  emits("update:show", false)
}

const confirm = () => {
  emits("confirm", [..._selected.value.values()])
  emits("update:show", false);
}

const handleOpen = () => {
  getGoodsList();
  getGoodsCate();
  getSelected();
}

const handleClose = () => {
  currentPageL.value = 1;
  totalL.value = 0;
  goodsList.value = new Map();
  loadingL.value = false;

  totalR.value = 0;
  currentPageR.value = 1;
  _selected.value = new Map();
}
</script>

<style scoped lang="scss">
.goods-list {
  display: flex;

  .side {
    flex: 1;

    .title {
      margin-bottom: 20px;
    }
  }

  .middle {
    width: 200px;
  }
}


.list{
  min-height: 500px;
  overflow: hidden;
  margin-top: 10px;

  .goods-item {
    width: 160px;
    height: 90px;
    float: left;
    border: 1px solid #eee;
    padding: 12px;
    box-sizing: border-box;
    margin-right: 20px;
    margin-bottom: 20px;
    border-radius: 5px;
  }

  .goods-item:nth-child(3n) {
    margin-right: 0;
  }

  .goods-item:hover {
    border: 1px solid #ccc;
  }

  .goods-item__selected {
    border: 1px solid var(--el-color-primary);
    color: var(--el-color-primary);
  }

  .top-wrapper {
    display: flex;
    align-items: center;
    height: 40px;

    .img {
      max-width: 40px;
      max-height: 40px;
      margin-right: 5px;
      border-radius: 2px;
      overflow: hidden;
    }

    .name {
      font-size: 12px;
    }
  }

  .line {
    margin-top: 10px;
    font-size: 12px;
  }
}

.button-list {
  margin-top: 10px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
}
</style>
